package com.lagou.edu.mvcframework.servlet;

import com.lagou.edu.mvcframework.annotations.*;
import com.lagou.edu.mvcframework.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.html.parser.Entity;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LgDispatcherServlet extends HttpServlet {

    private Properties properties = new Properties();

    private List<String> classNames = new ArrayList<>();

    private Map<String,Object> ioc = new HashMap<>();

//    private Map<String , Method> handlerMapping = new HashMap<>();

    private List<Handler> handlerMapping = new ArrayList<>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 1 加载配置文件 springmvc.properties
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);
        // 2 扫描注解
        doScanAnnotation("");

        // 3 初始化bean
        doInstance();

        // 4 实现注入
        doAutowired();

        // 5 构造HandlerMapping 处理器映射器 将配置好的url和Method建议映射
        initHandlerMapping();

        System.out.println("初始化完成...");
        // 等待请求，处理

    }

    //构造HandlerMapping 处理器映射器 将配置好的url和Method建议映射
    private void initHandlerMapping() {
        if(ioc.isEmpty()){return;}

        for(Map.Entry<String, Object> entry:ioc.entrySet()){
            Object value = entry.getValue();
            Class<?> aClass = value.getClass();
            if(!aClass.isAnnotationPresent(LagouRequestMapping.class)){continue;}
            LagouRequestMapping annotation = aClass.getAnnotation(LagouRequestMapping.class);
            String baseUrl = annotation.value();

            // 获取类上加了LagouSecurity注解的用户名
            List<String> userNameList = new ArrayList<>();
            //查询每个类上带有LagouSecurity注解
            LagouSecurity lagouSecurity = aClass.getAnnotation(LagouSecurity.class);
            //把带有权限注解的用户保存起来
            if(null != lagouSecurity){
                userNameList.addAll(Arrays.asList(lagouSecurity.userName()));
            }

            Method[] declaredMethods = aClass.getDeclaredMethods();
            for (Method declaredMethod : declaredMethods) {
                if(!declaredMethod.isAnnotationPresent(LagouRequestMapping.class)){continue;};
                LagouSecurity LagouSecurity2 = declaredMethod.getAnnotation(LagouSecurity.class);
                List<String> userNameList1 = new ArrayList<>();
                userNameList1.addAll(userNameList);
                if(null != LagouSecurity2){
                    userNameList1.addAll(Arrays.asList(LagouSecurity2.userName()));
                }


                LagouRequestMapping annotation1 = declaredMethod.getAnnotation(LagouRequestMapping.class);
                String methodUrl = annotation1.value();
                methodUrl = baseUrl + methodUrl;

                Handler handler = new Handler(value,declaredMethod, Pattern.compile(methodUrl),userNameList1);
                Parameter[] parameters = declaredMethod.getParameters();
                for (int i = 0; i < parameters.length; i++) {
                    Parameter parameter = parameters[i];
                    if(parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class){
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(), i);
                    }else{
                        handler.getParamIndexMapping().put(parameter.getName(),i);
                    }
                }


                handlerMapping.add(handler);
            }
        }
    }

    //实现注入
    private void doAutowired() {
        if(ioc.isEmpty()){return;}

        for(Map.Entry<String, Object> entry:ioc.entrySet()){
            String key = entry.getKey();
            Object value = entry.getValue();
            Class<?> aClass = value.getClass();
            Field[] declaredFields = aClass.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                if(declaredField.isAnnotationPresent(LagouAutowired.class)){
                    declaredField.setAccessible(true);
                    LagouAutowired annotation = declaredField.getAnnotation(LagouAutowired.class);
                    String beanName = annotation.value();
                    if("".equals(beanName)){
                        beanName = getLowerClassName(declaredField.getType().getSimpleName());
                    }
                    try {
                        declaredField.set(value, ioc.get(beanName));
                    } catch (IllegalAccessException e) {
                        System.out.println(e.getMessage());
                    }
                }
            }

        }
    }

    //初始化bean
    private void doInstance() {
        try{
            for (String className : classNames) {
                Class<?> aClass = Class.forName(className);
                if(aClass.isAnnotationPresent(LagouConroller.class)){
                    Object o = aClass.newInstance();
                    ioc.put(getLowerClassName(aClass.getSimpleName()), o);
                }else if(aClass.isAnnotationPresent(LagouService.class)){
                    Object o = aClass.newInstance();
                    LagouService annotation = aClass.getAnnotation(LagouService.class);
                    String value = annotation.value();
                    if(null == value || "".equals(value)){
                        ioc.put(getLowerClassName(aClass.getSimpleName()), o);
                    }else{
                        ioc.put(value, o);
                    }
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (Class<?> anInterface : interfaces) {
                        ioc.put(getLowerClassName(anInterface.getSimpleName()), aClass.newInstance());
                    }
                }
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }

    //扫描注解
    private void doScanAnnotation(String s)  {
        String path = this.getClass().getClassLoader().getResource("").getPath();
        File filePath = new File(path + properties.getProperty("scanPackage").replace('.', '/'));
        addClass(properties.getProperty("scanPackage"),filePath);
    }

    private String getLowerClassName(String name){
        char[] chars = name.toCharArray();
        if('A' <= chars[0] && chars[0] <= 'Z'){
            chars[0] +=32 ;
        }
        return String.valueOf(chars);
    }


    private void addClass(String s,File filePath) {


        if(filePath.isDirectory()) {
            for (File file : filePath.listFiles()) {
                addClass(s + "." + file.getName(),file);
            }
        }else if(filePath.getName().endsWith(".class")){
            String className = s .replace(".class", "");
            classNames.add(className);
        }
    }


    //加载配置文件 springmvc.properties
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Handler handler = getHandler(req);
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/plain; charset=utf-8");
        if(handler ==null){
            resp.getWriter().write("404 not found!!!");
        }

        Class<?>[] parameterTypes = handler.getMehtod().getParameterTypes();
        Object[] objects = new Object[parameterTypes.length];

        Map<String, String[]> parameterMap = req.getParameterMap();
        for (Map.Entry<String, String[]> stringEntry : parameterMap.entrySet()) {
            String join = StringUtils.join(stringEntry.getValue(), ",");
            if(!handler.getParamIndexMapping().containsKey(stringEntry.getKey())){
                continue;
            }

            Integer integer = handler.getParamIndexMapping().get(stringEntry.getKey());
            objects[integer] = join;
        }

        String[] usernames = parameterMap.get("username");
        String userName = StringUtils.join(usernames, ",");
        List<String> allowUserNames = handler.getUserName();
        if(allowUserNames.size() > 0 && !allowUserNames.contains(userName)){
            resp.getWriter().write("该用户无权限。");
            resp.getWriter().close();
        }

        Integer requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        objects[requestIndex] = req;
        Integer responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        objects[responseIndex] = resp;
        try {
            Object invoke = handler.getMehtod().invoke(handler.getConroller(), objects);
            resp.getWriter().write(invoke.toString());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private Handler getHandler(HttpServletRequest req) {

        if(handlerMapping.isEmpty()){
            return null;
        }
        for (Handler handler : handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(req.getRequestURI());
            if(!matcher.matches()){
                continue;
            }
            return  handler;
        }
        return null;
    }
}
